<?php

/**
 * 科目设置
 *
 * @version 1.0
 * @date 2013-12-13
 */
class DefaultController extends FController {

    public $user_school_list;
    public $user_subject_list;
    public $user_role_list;
	public function accessRules() {
		$config = array(
		'index' => 1
		);
		return ZRole::auth("subject", $config);
	}

	public function __common() {
		parent::init();

		if (empty($this->cLoginUser)) {
			$this->redirect($this->createUrl('/site/login'));
        } else {
            $userLoginUser = $this->cLoginUser;
            $this->user_role_list = isset($userLoginUser['cuser']['role_id']) ? $userLoginUser['cuser']['role_id'] : '';
            $this->user_school_list = isset($userLoginUser['cuser']['school']['school_id']) ? $userLoginUser['cuser']['school']['school_id'] : '';
            $this->user_subject_list = isset($userLoginUser['cuser']['school']['subject_id']) ? $userLoginUser['cuser']['school']['subject_id'] : '';
		}

		$this->commonScript();
		Yii::app()->clientScript->registerCssFile(THEME_CSS_URL . '/module_Sip.css');
	}

	/**
     * 	@ 列表显示
     * 	@ yindebin 
     * 	@ 2013-12-13 am
     *
     */
	public function actionIndex() {
		$this->__common();
		$conn = Yii::app()->db;
		$this->title = '科目信息设置';
		$s['subject_code'] = $subject_code = trim(Yii::app()->request->getParam('subject_code'));
		$s['subject_name'] = $subject_name = trim(Yii::app()->request->getParam('subject_name'));
		$s['is_display'] = $is_display = trim(Yii::app()->request->getParam('is_display'));
        $s = Func::dis_input($s);
		$s = Func::fAddslashes($s);
		$where = ' AND "is_del" = 0 ';
		$order = '';
		# 条件拼接 #

		if (Func::check_search($s['subject_code'])) {
			$where.=' AND "subject_code" LIKE '."'%".$s['subject_code']."%'";
		}
		if (Func::check_search($s['subject_name'])) {
			$where.=' AND "subject_name" LIKE '."'%".$s['subject_name']."%'";
		}
		if (!empty($s['is_display'])) {
			$where.=' AND "disabled" ="1" ';
		}

        //权限判断
        if($this->user_role_list !=1 && !empty($this->user_subject_list)){
            $where .= ' AND "subject_id" IN ('.$this->user_subject_list.')';
        }
		#  排序  #
		$order.= ' ORDER BY "subject_code"  ';
		$select = 'SELECT * FROM "{{subject}}" ';
		$sql = ' WHERE "subject_id">0 ' . $where;

		$selectSql = $select . $sql . $order;
		$countSql = 'SELECT COUNT(*) FROM "{{subject}}" ' . $sql;
		$data = ZCommon::getDaoPageList($selectSql, $countSql, 8);
		$pageUrl = $this->createUrl('/subject/default/index', $s);

		$this->render('index', array(
		'data' => $data['listDatas'],
		'pages' => $data['pages'],
		'serch' => $s,
		'pageUrl' => $pageUrl,
		'search' => $s
		));
	}

	/**
     * 	@ 更新
     * 	@ yindebin am
     * 	@ 2013-12-13
     *
     */
	public function actionUpdate() {
		//$this->__common();

		$this->title = '科目信息设置';
		$this->layout = "//layouts/main_window";

		$subject_id = (int) Yii::app()->request->getparam('subject_id');
		$subject_id = (!empty($_POST['info']['subject_id'])) ? $_POST['info']['subject_id'] : $subject_id;

		$model = Subject::model()->findByPk($subject_id);

		if(!empty($model)){
			$data1 = $model->attributes;
		}

		if (empty($model)) {
			$this->redirect($this->createUrl('index'));
			exit;
		}

		if (!empty($_POST['submit'])) {
			$data = ZTask::dis_input($_POST['info']);
			$data['disabled'] = (!empty($data['disabled'])) ? $data['disabled'] : 0;

			$data['subject_code'] = strtolower($data['subject_code']);

			$checkCode = $this->isCheckSubjectCode($data['subject_code'],$data['subject_id']);
			if (!empty($checkCode)){
				if($checkCode['is_del'] == 1){
					$this->frameAjaxMessage(null, '相同科目代码在回收站中,不可重复使用!');
				}else{
					$this->frameAjaxMessage(null, '科目代码已被占用!');
				}

				//$this->runShowMessge('/subject/default/index','科目代码已被占用!');
				exit;
			}

			$data['update_user'] = $this->cLoginUser['cuser']['id'];
			$data['update_time'] = time();
			$model->attributes = $data;

			if ($model->save()) {
				$this->frameAjaxMessage(null,null,true);
				//$this->runShowMessge('index');
				exit;
			} else {
				$this->frameAjaxMessage(null,'更新失败');
				//$this->runShowMessge('index','更新失败');
				exit;
			}
		} else {
			$this->render('update', array(
			'data' => $model->attributes,
			));
		}
	}

	/**
     * 	@ 添加
     * 	@ yindebin
     * 	@ 2013-12-13 am
     *
     */
	public function actionAdd() {

		$this->title = '科目信息设置';
		$this->layout = "//layouts/main_window";

		if (!empty($_POST['submit'])) {
			$conn = Yii::app()->db;
			$data = ZTask::dis_input($_POST['info']);

			$data['subject_code'] = strtolower($data['subject_code']);

			$checkCode = $this->isCheckSubjectCode($data['subject_code']);

			if (!empty($checkCode)) {
				if($checkCode['is_del']){
					$this->frameAjaxMessage(null, '相同科目代码在回收站中,不可重复使用!');
				}else{
					$this->frameAjaxMessage(null, '科目代码已被占用!');
				}

				exit;
			}

			$data['create_user'] = $this->cLoginUser['cuser']['id'];
			$data['create_time'] = time();
			$data['update_user'] = $this->cLoginUser['cuser']['id'];
			$data['update_time'] = time();

			$data['disabled'] = (!empty($data['disabled'])) ? $data['disabled'] : 0;
			$sql = 'INSERT INTO "{{subject}}" ("subject_name","subject_code","description","disabled","create_user","create_time","update_user","update_time")  VALUES(:subject_name,:subject_code,:description,:disabled,:create_user,:create_time,:update_user,:update_time)';

			$result = $conn->createcommand($sql);

			$result->bindParam(':subject_name', $data['subject_name'], PDO::PARAM_STR);
			$result->bindParam(':subject_code', $data['subject_code'], PDO::PARAM_STR);
			$result->bindParam(':description', $data['description'], PDO::PARAM_STR);
			$result->bindParam(':disabled', $data['disabled'], PDO::PARAM_STR);
			$result->bindParam(':create_user', $data['create_user'], PDO::PARAM_STR);
			$result->bindParam(':create_time', $data['create_time'], PDO::PARAM_STR);
			$result->bindParam(':update_user', $data['update_user'], PDO::PARAM_STR);
			$result->bindParam(':update_time', $data['update_time'], PDO::PARAM_STR);

			$row = $result->execute();
			if (!empty($row)) {
				//$this->runShowMessge('index');
				$this->frameAjaxMessage(null,null,true);
				exit;
			} else {
				$this->frameAjaxMessage(null,'更新失败');
				//$this->runShowMessge('index', '更新失败');
				exit;
			}
		} else {
			$this->render('add');
		}
	}

	/**
     * @ 判断代码是否已被占用
     * @ yindebin
     * @ 2013-12-28
     */
	protected function isCheckSubjectCode($subject_code,$subject_id=''){
		$conn = Yii::app()->db;


		$where = ' AND "subject_code" = '."'".$subject_code."'";
		if (!empty($subject_id)){
			$where.= ' AND "subject_id" != '."'".$subject_id."'";
		}

		$sql = 'SELECT "subject_id","is_del"  FROM "{{subject}}" WHERE 1=1 '.$where;


		return $query = $conn->createCommand($sql)->queryRow();

	}


	/**
     * 	@ 删除
     * 	@ yindebin
     * 	@ 2013-12-13 am
     *
     */
	public function actionDelete() {
		$conn = Yii::app()->db;

		$subject_id = (int) Yii::app()->request->getparam('subject_id');
		if (!empty($subject_id)) {
			$model = Subject::model()->findByPk($subject_id);
			if (empty($model)) {
				echo 2;
				exit;
			}
			$sql = 'UPDATE "{{subject}}" SET "is_del" = 1 WHERE "subject_id" = '.$subject_id;
			$query = $conn->createCommand($sql)->execute();
			if (!empty($query)) {
				$update = 'UPDATE "{{question_type}}" SET "is_del" = 1 WHERE "subject_id" = '.$subject_id;
				$query = Yii::app()->db->createCommand($update)->execute();
				echo 1;
			} else {
				echo 2;
			}
		} else {
			echo 2;
		}
	}

	/**
     * @ 批量删除
     * @ yindebin
     * @ 2014-01-06
     */
	public function actionDelete_all(){
		$subject_id = Yii::app()->request->getparam('subject_id');
		if (!empty($subject_id)) {

			$select = 'SELECT "question_id" FROM "{{question_type}}" WHERE "subject_id" IN ('.$subject_id.') AND "is_del" = 0 ';
			$data = Yii::app()->db->createCommand($select)->queryRow();
			if(!empty($data)){
				echo 3;
				exit;
			}
			$delete = 'UPDATE "{{subject}}" SET "is_del" = 1 WHERE "subject_id" IN ('.$subject_id.')';
			$query = Yii::app()->db->createCommand($delete)->execute();
			if(!empty($query)){
				$delete = 'UPDATE "{{question_type}}" SET "is_del" = 1 WHERE "subject_id" IN ('.$subject_id.')';
				$query = Yii::app()->db->createCommand($delete)->execute();
			}
			echo 1;
		} else {
			echo 2;
		}
	}

	/**
     * @ 批量删除题型
     * @ yindebin
     * @ 2014-01-06
     */
	public function actionDelete_q_all(){
		$question_id = Yii::app()->request->getparam('question_id');
		if (!empty($question_id)) {

			$delete = 'UPDATE "{{question_type}}" SET "is_del" = 1 WHERE "question_id" IN ('.$question_id.')';

			if ($query = Yii::app()->db->createCommand($delete)->execute()) {
				echo 1;
			} else {
				echo 2;
			}
		} else {
			echo 2;
		}
	}

	/**
     *  @ 题型列表
     *  @ yindebin
     *  @ 2013-12-27
     */
	public function actionQuestion_list(){
		$this->__common ();
		$this->title = "题型设置";
		$s['subject_id'] = (int)Yii::app()->request->getParam('subject_id');

		$where = "";
		$order = ' ORDER BY "question_code" ';

		$where .= ' AND "subject_id" ='.$s['subject_id'].' AND "is_del" = 0 ';

		$sql = 'SELECT * FROM "{{question_type}}"  ';
		$condition = " WHERE 1=1 ".$where;

		$selectSql = $sql.$condition.$order;
		$countSql = 'SELECT COUNT(*) FROM "{{question_type}}" WHERE 1=1 '.$where;

		$data = ZCommon::getDaoPageList($selectSql, $countSql, 8);

		$pageUrl = $this->createUrl('/subject/default/question_list',$s);

		$this->render('question_list',array('data' => $data['listDatas'],'pages'=>$data['pages'],'pageUrl'=>$pageUrl,'subject_id'=>$s['subject_id']));

	}

	/**
     * @ 添加题型
     * @ yindebin
     * @ 2013-12-27
     */
	public function actionAdd_question(){
		$this->title = "题型设置";
		$this->layout = "//layouts/main_window";
		if (! empty ( $_POST ['submit'] )) {
			$data = ZTask::dis_input($_POST ['info']);

			$data ['question_id'] = 0;

			$data ['disabled'] = (! empty ( $data ['disabled'] )) ? $data ['disabled'] : 0;
			$data ['aritificial'] = (! empty ( $data ['aritificial'] )) ? $data ['aritificial'] : 0;
			$data['question_code'] = strtolower($data['question_code']);
			if(!empty($data['question_code'])){
				$question_type = QuestionType::model()->find('"question_code" = :question_code ',array(":question_code"=> $data['question_code']));
				if(!empty($question_type)){
					if($question_type->is_del == 1){
						$this->frameAjaxMessage(null, '相同题型代码在回收站中,不可重复使用!');
					}else{
						$this->frameAjaxMessage(null, '题型代码已被占用!');
					}

					exit;
				}
			}
			$model = new QuestionType ();

			$data['create_user'] = $this->cLoginUser['cuser']['id'];
			$data['create_time'] = time();
			$data['update_user'] = $this->cLoginUser['cuser']['id'];
			$data['update_time'] = time();

			$model->attributes = $data;

			if ($model->save ()) {
				$this->frameAjaxMessage (  '/subject/default/question_list/subject_id/'.$data['subject_id']);
				exit;
			} else {
				$this->frameAjaxMessage ( null, "添加失败" );
				exit;
			}
		} else {

			#  取科目信息   #
			$subject_id = Yii::app ()->request->getParam ( 'subject_id' );
			if (empty ( $subject_id )){
				$this->frameAjaxMessage ('/subject/default/question_list/subject_id/'.$subject_id);
				exit;
			}

			$subject_type = Subject::model ()->findByPk ( $subject_id );
			if (empty ( $subject_type )){
				$this->frameAjaxMessage ('/subject/default/question_list/subject_id/'.$subject_id );
				exit;
			}

			$this->render ( 'add_question', array ('subject_id' => $subject_id ,'subject_type'=>$subject_type) );
		}
	}

	/**
     * @ 更新题型信息
     * @ yindebin
     * @ 2013-12-27
     */
	public function actionUpdate_question(){
		$this->title = "题型设置";
		$this->layout = "//layouts/main_window";

		$question_id = ( int ) Yii::app ()->request->getparam ( 'question_id' );
		$question_id = (! empty ( $_POST ['info'] ['question_id'] )) ? $_POST ['info'] ['question_id'] : $question_id;

		$subject_id = (int)	Yii::app()->request->getparam('subject_id');

		$model = QuestionType::model ()->findByPk ( $question_id );


		if (empty ( $model )) {
			$this->frameAjaxMessage ('/subject/default/question_list/subject_id/'.$subject_id );
			//$this->runShowMessge ( '/subject/default/question_list/subject_id/'.$subject_id, "" );
			exit ();
		}

		if (! empty ( $_POST ['submit'] )) {
			$data = ZTask::dis_input($_POST['info']);
			$data ['disabled'] = (! empty ( $data ['disabled'] )) ? $data ['disabled'] : 0;
			$data ['aritificial'] = (! empty ( $data ['aritificial'] )) ? $data ['aritificial'] : 0;
			$data['question_code'] = strtolower($data['question_code']);
			# 判断代码是否存在 #
			$question_type = QuestionType::model()->find('"question_code" = :question_code AND "question_id" != \''.$data['question_id'].'\'',array(":question_code"=> $data['question_code']));
			if(!empty($question_type)){
				if($question_type->is_del == 1){
					$this->frameAjaxMessage(null, '相同题型代码在回收站中,不可重复使用!');
				}else{
					$this->frameAjaxMessage(null,'题型代码已被占用!');
				}

				exit;
			}
			$data['update_user'] = $this->cLoginUser['cuser']['id'];
			$data['update_time'] = time();
			$model->attributes = $data;
			if ($model->save ()) {
				$this->frameAjaxMessage ('/subject/default/question_list/subject_id/'.$data['subject_id']);
				//$this->runShowMessge ( '/subject/default/question_list/subject_id/'.$data['subject_id'] );
				exit;
			} else {
				$this->frameAjaxMessage (null, "更新失败" );
				//$this->runShowMessge ( '/subject/default/question_list/subject_id/'.$data['subject_id'], "更新失败" );
				exit;
			}
		} else {

			$question_data = $model->attributes;
			$subject_data = Subject::model()->findByPk($subject_id);

			$this->render ( 'update_question',array('question_data'=> $question_data ,'subject_data'=>$subject_data) );
		}
	}

	/**
	 * @ 删除题型
	 * @ yindebin
	 * @ 2013-12-27 pm
	 *
	 */
	public function actionDelete_question() {
		$question_id = ( int ) Yii::app ()->request->getparam ( 'question_id' );
		$subject_id = (int) Yii::app()->request->getparam('subject_id');

		if (! empty ( $question_id )) {

			$model = QuestionType::model ()->findByPk ( $question_id );

			if (empty ( $model )) {
				echo 2;
				exit ();
			}

			//$model->is_del = '1';

			if ($model->delete('"question_id" = '.$question_id)) {

				echo 1;
				exit ();

			} else {
				echo 2;
				exit ();
			}
		} else {
			echo 2;
		}
	}
	/**
     * 	@ 导出Excel
     * 	@ yindebin
     * 	@ 2013-12-13
     *
     *  @update jinyue.wang
     *  @更新页面相关信息（增加信息判断）
     */
	public function actionImportExcel() {

		$conn = Yii::app()->db;

		$s['subject_code'] = $subject_code = Yii::app()->request->getParam('subject_code');
		$s['subject_name'] = $subject_name = Yii::app()->request->getParam('subject_name');
		$s['is_display'] = $is_display = Yii::app()->request->getParam('is_display');

		# 得到科目信息 #
		$where = $order =  '';
		$where.= ' AND "is_del" = 0';


		# 条件拼接 #
		if (!empty($s['subject_code'])) {
			$where.=' AND "subject_code" LIKE '."'%".$s['subject_code']."%'";
		}
		if (!empty($s['subject_name'])) {
			$where.=' AND "subject_name" LIKE '."'%".$s['subject_name']."%'";
		}
		if (!empty($s['is_display'])) {
			$where.=' AND "disabled" ="1" ';
		}

		$selectSql = 'SELECT * FROM "{{subject}}"';
		$sql = " WHERE 1=1 " . $where;
		$select = $selectSql . $sql . $order;
		$data = $conn->createcommand($select)->queryAll();


		if (!empty($data)) {
			spl_autoload_unregister(array('YiiBase', 'autoload'));
			include_once(dirname(dirname(dirname(dirname(__FILE__)))) . '/extensions/PHPExcel.php');
			include_once(dirname(dirname(dirname(dirname(__FILE__)))) . '/extensions/PHPExcel/IOFactory.php');

			$objPHPExcel = new PHPExcel();
			$objPHPExcel->setActiveSheetIndex(0)
			->setCellValue('A1', '序号')
			->setCellValue('B1', '科目代码')
			->setCellValue('C1', '科目名称')
			->setCellValue('D1', '备注');
			$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(11);
			$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(25);
			$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(30);
			$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(45);
			$i = 2;

			foreach ($data as $v) {

				$objPHPExcel->setActiveSheetIndex(0)
				->setCellValue('A' . $i, ($i - 1))
				->setCellValue('B' . $i, $v['subject_code'])
				->setCellValue('C' . $i, $v['subject_name'])
				->setCellValue('D' . $i, $v['description']);
				$i++;
			}
			$objPHPExcel->setActiveSheetIndex(0);
			$file_nams = "科目";
			$file_nams .= ".xls";

			if (preg_match("/MSIE/", $_SERVER["HTTP_USER_AGENT"])) {
				$file_nams = urlencode($file_nams);
				$file_nams = str_replace("+", "%20", $file_nams); // 替换空格
			}
			ob_end_clean();
			header("Content-Type: application/vnd.ms-excel;charset=utf-8");
			header("Content-Disposition: attachment; filename=" . $file_nams);
			header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
			header('Expires:0');
			header('Pragma:public');

			$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
			$objWriter->save('php://output');

			Yii::app()->end();
			spl_autoload_register(array('YiiBase', 'autoload'));
		}else{
			//没有相关信息
			echo 1;
			exit;
		}
	}

}